package com.zw.transition.services;

import com.zw.transition.common.JsonResult;
import com.zw.transition.entity.*;
import com.zw.transition.mapper.FlowMapper;
import com.zw.transition.mapper.UserMapper;
import com.zw.transition.util.BeanUtil;
import com.zw.transition.util.FileUtils;
import com.zw.transition.util.ServletUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Author: China.sgl
 * @Date: 2019/9/16 09:11
 */
@Service
@SuppressWarnings("all")
public class IndexService {
    @Value("${user.upload.path}")
    private String uploadPath;
    @Value("${server.url}")
    private String serverUrl;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private LogService logService;
    @Autowired
    private FlowMapper flowMapper;
    @Autowired
    private AssemblyService assemblyService;

    /**
     * 修改密码
     */
    public int updatePwd(User user) {
        user.setPwd(new SimpleHash("MD5", user.getPwd(), ByteSource.Util.bytes(user.getAccount()), 8).toString());
        return userMapper.updatePwd(user);
    }

    /**
     * 申请质检列表
     */
    public List<FlowTrans> findApplyList(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) return null;
        List<FlowTrans> routes = flowMapper.findApplyList(parse);
        return routes;
    }

    /**
     * 申请质检列表
     */
    public List<FlowTrans> findApplyListByAssembling(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) return null;
        List<FlowTrans> routes = flowMapper.findApplyListByAssembling(parse);
        return routes;
    }

    /**
     * 质检列表
     */
    public List<FlowTrans> findCheckListByAssembling(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) return null;
        List<FlowTrans> routes = flowMapper.findCheckListByAssembling(parse);
        return routes;
    }

    /**
     * 申请质检列表
     */
    public List<FlowTrans> findApplyListByRepair(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) return null;
        List<FlowTrans> routes = flowMapper.findApplyListByRepair(parse);
        return routes;
    }

    /**
     * 完成的申请质检列表
     */
    public List<FlowRoute> findCompleteApplyList(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) {
            return null;
        }
        List<FlowRoute> routes = flowMapper.findCompleteApplyList(parse);
        return routes;
    }

    /**
     * 完成的质检列表
     */
    public List<FlowRoute> findCompleteApplyList1(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) {
            return null;
        }
        List<FlowRoute> routes = flowMapper.findCompleteApplyList1(parse);
        return routes;
    }

    /**
     * 完成的质检列表
     */
    public List<FlowRoute> findCompleteApplyList2(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) {
            return null;
        }
        List<FlowRoute> routes = flowMapper.findCompleteApplyList2(parse);
        return routes;
    }

    /**
     * 申请质检
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult apply(FlowTrans transApply) {
        JsonResult jsonResult = new JsonResult();
        //根据转序单信息获取路线
        FlowRoute route = flowMapper.getFlowRouteByTrans(transApply);
        transApply.setStatus(1);
        User u = (User) ServletUtils.getSession().getAttribute("user");
        transApply.setApplyCode(u.getAccount());
        transApply.setApplyName(u.getName());
        transApply.setApplyTime(new Date());
        transApply.setApplyDept(u.getBranch());
        transApply.setIsDel(0);
        //如果不是返修票
        if (transApply.getType().intValue() != 3) {
            //如果是厂级转序
            if (transApply.getTransMode().intValue() == 1) {
                route.setApplyNum(transApply.getNum());
                // 修改路线表数量 可申请数减少， 已申请数增加
                int num = flowMapper.updateRouteApply(route);
                if (num == 0) {
                    FlowRoute flowRoute = flowMapper.getFlowRouteByPrimaryKey(route.getId());
                    jsonResult.setType(JsonResult.ResultType.ERROR);
                    jsonResult.setMsg("申请失败，因申请数量超过可申请数量,可申请数量为" + flowRoute.getMayApplyNum() + "个零件！");
                } else {
                    //插入转序单数据
                    flowMapper.addTrans(transApply);
                    jsonResult.setType(JsonResult.ResultType.SUCCESS);
                    jsonResult.setMsg("申请成功！");
                }
            }
            //如果是车间级转序
            else if (transApply.getTransMode().intValue() == 2) {
                //根据转序单信息获取工序
                FlowProcess process = flowMapper.getFlowProcessByRouteIdAndProcessAndOrderNum(route.getId(), transApply.getProcess(), transApply.getOrderNum());
                process.setApplyNum(transApply.getNum());
                // 修改工序表数量 可申请数减少， 已申请数增加
                int num = flowMapper.updateProcessApply(process);
                if (num == 0) {
                    FlowRoute flowRoute = flowMapper.getFlowRouteByPrimaryKey(route.getId());
                    jsonResult.setType(JsonResult.ResultType.ERROR);
                    jsonResult.setMsg("申请失败，因申请数量超过可申请数量,可申请数量为" + flowRoute.getMayApplyNum() + "个零件！");
                } else {
                    //如果要当前路线下首序工序
                    if (process.getOrderNum() == 1) {
                        route.setApplyNum(transApply.getNum());
                        flowMapper.updateRouteApply(route);
                    }
                    //如果是划线直接走质检完成
                    if (process.getProcess().equals("划线")) {
                        FlowSheet sheet = flowMapper.getSheet(route);
                        //插入转序单数据
                        flowMapper.addTrans(transApply);
                        //如果不是返修转序
                        FlowCheck check = new FlowCheck();
                        check.setTransId(transApply.getId());
                        success(check);
                    } else {
                        //插入转序单数据
                        flowMapper.addTrans(transApply);
                    }
                    jsonResult.setType(JsonResult.ResultType.SUCCESS);
                    jsonResult.setMsg("申请成功！");
                }
            }
        }
        //如果是返修票
        else {
            //FlowSheet sheet = flowMapper.getFlowSheetByInfo(transApply.getProdNo(),transApply.getProName(),transApply.getDrawNo());
            flowMapper.addTrans(transApply);
            jsonResult.setType(JsonResult.ResultType.SUCCESS);
            jsonResult.setMsg("申请成功！");
        }
        return jsonResult;
    }

    /**
     * 取消申请质检 厂级
     */
    @Transactional(rollbackFor = Exception.class)
    public int cancelApply(FlowTrans trans) {
        FlowTrans flowTrans = flowMapper.getTrans(trans.getId());
        FlowRoute flowRoute = flowMapper.findCurRoute(flowTrans);
        flowRoute.setApplyNum(flowTrans.getNum());
        int res = flowMapper.updateRouteApplyToCancelApply(flowRoute);
        //删除转序单
        trans.setIsDel(1);
        res += flowMapper.updateFlowTransIsdel(trans);
        //如果该序是首序则修改下料状态为未下料
//        if (flowRoute.getOrderNo() == 10 && !flowRoute.getRoute().equals("原料")){
//            FlowSheet flowSheet = flowMapper.getSheet(flowRoute);
//            flowSheet.setCutStatus(null);
//            flowMapper.updateFlowSheetCutStatusByPrimary(flowSheet);
//        }
        return res;
    }

    /**
     * 取消申请质检 车间级
     */
    @Transactional(rollbackFor = Exception.class)
    public int cancelApplyForProcess(FlowTrans trans) {
        FlowTrans flowTrans = flowMapper.getFlowTransByPrimaryKey(trans.getId());
        FlowRoute flowRoute = flowMapper.getFlowRouteByPrimaryKey(trans.getRouteId());
        FlowProcess flowProcess = flowMapper.getFlowProcessByPrimaryKey(trans.getProcessId());
        flowProcess.setApplyNum(flowTrans.getNum());
        int res = flowMapper.updateRouteApplyToCancelApplyByProcess(flowProcess);
        //删除转序单
        trans.setIsDel(1);
        res += flowMapper.updateFlowTransIsdel(trans);
        return res;
    }

    /**
     * 质检列表
     */
    public List<FlowTrans> findCheckList(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) return null;
        return flowMapper.findCheckList(parse);
    }

    /**
     * 质检列表
     */
    public List<FlowTrans> findCheckListByRepair(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) return null;
        return flowMapper.findCheckListByRepair(parse);
    }


    /**
     * 转序接收列表
     */
    public List<FlowTrans> findRecList(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) return null;
        List<FlowTrans> routes = flowMapper.findRecList(parse);
        return routes;
    }

    /**
     * 转序接收列表
     */
    public List<FlowTrans> findRecListListByRepair(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) return null;
        List<FlowTrans> routes = flowMapper.findRecListListByRepair(parse);
        return routes;
    }

    /**
     * 质检驳回
     */
    @Transactional(rollbackFor = Exception.class)
    public int reject(FlowCheck check) {
        FlowTrans trans = flowMapper.getTrans(check.getTransId());
        if (trans.getStatus() != 1) {
            return 0;
        }
        trans.setStatus(4);
        flowMapper.updateFlowTransStatusByPrimaryKey(trans);
        User u = (User) ServletUtils.getSession().getAttribute("user");
        check.setTransId(trans.getId());
        check.setCheckCode(u.getAccount());
        check.setCheckName(u.getName());
        if (u.getBranchName() != null) {
            check.setCheckDept(u.getBranchName());
        }
        check.setCheckTime(new Date());
        check.setResult("质检不合格");
        FlowCheck dbCheck = flowMapper.getFlowCheckByTransId(check.getTransId());
        int operationResult = 0;
        if (check.getYield() == null) {
            check.setYield(0);
        }
        if (dbCheck != null) {
            check.setId(dbCheck.getId());
            operationResult = flowMapper.updateFlowCheckForRejectByPrimaryKey(check);
        } else {
            operationResult = flowMapper.insertFlowCheckForRejectByPrimaryKey(check);
        }
        return operationResult;
    }

    /**
     * 质检合格
     */
    @Transactional(rollbackFor = Exception.class)
    public int success(FlowCheck check) {
        Date currentDate = new Date();
        FlowTrans trans = flowMapper.getTrans(check.getTransId());

        if (trans.getStatus() != 1) {
            return 0;
        }
        User u = (User) ServletUtils.getSession().getAttribute("user");
        u = flowMapper.getUserById(u.getId());
        check.setCheckCode(u.getAccount());
        check.setCheckName(u.getName());
        check.setCheckTime(currentDate);
        if (u.getBranch() != null) {
            check.setCheckDept(u.getBranch());
        }
        check.setYield(check.getYield() == null ? 0 : 1);
        check.setResult("质检合格");
        trans.setStatus(2);
        flowMapper.updateFlowTransStatusByPrimaryKey(trans);
        FlowCheck dbCheck = flowMapper.getFlowCheckByTransId(check.getTransId());
        int operationResult = 0;
        if (check.getYield() == null) {
            check.setYield(0);
        }
        //如果是制作件工艺卡
        if (trans.getType().intValue() == 1) {
            //如果是厂级转序
            if (trans.getTransMode() == 1) {
                FlowRoute cur = flowMapper.findCurRoute(trans);
                if (cur.getApplyNum() >= cur.getCheckNum()) {
                    if (dbCheck != null) {
                        check.setId(dbCheck.getId());
                        operationResult = flowMapper.updateFlowCheckForSuccessByPrimaryKey(check);
                    } else {
                        operationResult = flowMapper.insertFlowCheckForSuccessByPrimaryKey(check);
                    }
                    FlowRoute next = flowMapper.findNextRoute(cur);
                    FlowSheet sheet = flowMapper.getSheet(cur);
                    //获取零件总数
                    int totalNum = sheet.getDrawNum() - sheet.getInvalid();
                    cur.setCheckNum(cur.getCheckNum() + trans.getNum());
                    cur.setCanChange(2);
                    if (totalNum == cur.getCheckNum().intValue()) {
                        cur.setStatus(4);
                    } else {
                        cur.setStatus(3);
                    }
                    cur.setRouteDate(currentDate);
                    flowMapper.updateRouteCheck(cur);
                    //获取最后一道序
                    FlowRoute lastRoute = getLastRoute(cur);
                    if (null != next && "转储".equals(next.getRoute())) {
                        trans.setStatus(3);
                        next.setRecNum(next.getRecNum() + trans.getNum());

                        if (totalNum == next.getRecNum()) {
                            next.setStatus(4);
                        } else {
                            next.setStatus(4);
                            //检测改生产令全部最后一道序是否全部完成或未完成修改生产任务表的生产状态
                        }
                        flowMapper.updateRouteRecNum(next);
                        next.setRouteDate(currentDate);
                        flowMapper.updateRouteRouteDate(next);
                        //获取对应的库存信息如果没有则插入数据库，有则更新数量
                        //执行入库
                        HalfStore store = new HalfStore();
                        store.setSheetId(sheet.getId());
                        store.setNum(trans.getNum());
                        BeanUtil.copy(sheet, store);
                        store.setStoreAddr(trans.getApplyDept());
                        //生成入库记录
                        AsseHalfStoreRecord record = new AsseHalfStoreRecord();
                        //根据 生产令编号 部分 专业 图号 获取对应的库存
                        HalfStore existHalfStore = flowMapper.getExistHalfStore(store);
                        if (existHalfStore != null) {
                            existHalfStore.setNum(existHalfStore.getNum() + trans.getNum());
                            if (existHalfStore.getNum() <= existHalfStore.getDrawNum()) {
                                flowMapper.updateHalfStoreNumByPrimary(existHalfStore);
                                record.setStoreId(existHalfStore.getId());
                            } else {
                                Exception exception = new Exception();
                                exception.printStackTrace();
                            }
                        } else {
                            flowMapper.insertHalfStore(store);
                            record.setStoreId(store.getId());
                        }
                        record.setProdNo(sheet.getProdNo());
                        record.setSpecial(sheet.getSpecial());
                        record.setPartId(sheet.getPartId());
                        record.setDrawName(sheet.getDrawName());
                        record.setDrawNo(sheet.getDrawNo());
                        record.setDrawNum(trans.getNum());
                        record.setWeight(sheet.getWeight());
                        record.setQuality(sheet.getQuality());
                        record.setSpec(sheet.getSpec());
                        record.setStoreType(1);
                        record.setRecordType(1);
                        record.setStoreAddr(trans.getApplyDept());
                        record.setStorageRegisterCode(trans.getApplyCode());
                        record.setStorageTime(currentDate);
                        flowMapper.insertAsseHalfStoreRecord(record);
                        trans.setRecordId(record.getId());
                        flowMapper.updateSheetTrans(trans);
                    }
                    //如果最后道序是铆焊则根据接收数量判断把状态进行更改，部分接收是3，完全接收是4
                    else if (next.getRoute().equals("参焊") && lastRoute.getRoute().equals("参焊") && lastRoute.getOrderNo() == next.getOrderNo()) {
                        trans.setStatus(3);
                        //获取零件总数
                        FlowRoute totalNumRoute = flowMapper.getFirstRoute(cur);
                        next.setRecNum(next.getRecNum() + trans.getNum());
                        next.setMayApplyNum(0);
                        if (totalNumRoute.getRecNum().intValue() > next.getRecNum().intValue()) {
                            next.setStatus(3);
                        } else {
                            next.setStatus(4);
                        }
                        flowMapper.updateRouteRecNum(next);
                    }
                    //如果该序全部转序则修改对应任务的状态
                    if (cur.getRoute().equals("铆焊") || cur.getRoute().equals("机加")) {
                        int routeCount = flowMapper.getRoteCountBySheetId(cur.getRoute(), sheet.getProdNo());
                        int routeCompleteCount = flowMapper.getRoteCompleteCountBySheetId(cur.getRoute(), sheet.getProdNo());
                        Date start = currentDate;
                        Date end = currentDate;
                        if (routeCount == routeCompleteCount) {
                            String tasCod = "";
                            if (cur.getRoute().equals("铆焊")) {
                                tasCod = "t11";
                            } else if (cur.getRoute().equals("机加")) {
                                tasCod = "t14";
                            }
                            flowMapper.updateTaskStatusAndEndDat(sheet.getProdNo(), tasCod, end, u.getDeptId(), u.getId());
                        } else {
                            String tasCod = "";
                            if (cur.getRoute().equals("铆焊")) {
                                tasCod = "t11";
                            } else if (cur.getRoute().equals("机加")) {
                                tasCod = "t14";
                            }
                            Date dataBaseStartDate = flowMapper.getDataBaseStartDate(sheet.getProdNo(), tasCod);
                            if (dataBaseStartDate == null) {
                                flowMapper.updateTaskStatusAndStartDat(sheet.getProdNo(), tasCod, start, u.getDeptId(), u.getId());
                            }
                        }

                    }
                    //flowMapper.updateCheckTrans(trans);
                    //检测改生产令全部最后一道序是否全部完成或未完成修改生产任务表的生产状态
                    checkLastRouteIsFinished(sheet);

                } else {
                    return 0;
                }

            }
            //如果是车间级转序
            else if (trans.getTransMode() == 2) {
                FlowRoute curRoute = flowMapper.findCurRoute(trans);
                FlowProcess curProcess = flowMapper.getFlowProcessByRouteIdAndProcessAndOrderNum(curRoute.getId(), trans.getProcess(), trans.getOrderNum());
                FlowSheet sheet = flowMapper.getSheet(curRoute);
                if (curProcess.getApplyNum() >= curProcess.getCheckNum()) {
                    //检测改生产令全部最后一道序是否全部完成或未完成修改生产任务表的生产状态
                    checkLastRouteIsFinished(sheet);
                    if (dbCheck != null) {
                        check.setId(dbCheck.getId());
                        operationResult = flowMapper.updateFlowCheckForSuccessByPrimaryKey(check);
                    } else {
                        operationResult = flowMapper.insertFlowCheckForSuccessByPrimaryKey(check);
                    }
                    //获取零件总数
                    int totalNum = sheet.getDrawNum() - sheet.getInvalid();
                    curProcess.setCheckNum(curProcess.getCheckNum() + trans.getNum());
                    curRoute.setCanChange(2);
                    if (totalNum == curProcess.getCheckNum().intValue()) {
                        curProcess.setStatus(4);
                    } else {
                        curProcess.setStatus(3);
                    }
                    curProcess.setProcessDate(currentDate);
                    flowMapper.updateProcessCheck(curProcess);
                    //如果是全部转序
                    if (curProcess.getStatus() == 4) {
                        //获取最后一道工序
                        FlowProcess lastProcess = flowMapper.getLastProcess(curProcess);
                        //用来判断本工序是否是该路线的最后一序,如果是最后一道工序
                        if (curProcess.getProcess().equals(lastProcess.getProcess()) && curProcess.getOrderNum().intValue() == lastProcess.getOrderNum().intValue()) {
                            //更新本路线信息
                            int totalRouteNum = sheet.getDrawNum() - sheet.getInvalid();
                            curRoute.setCheckNum(curProcess.getCheckNum());
                            curRoute.setCanChange(2);
                            if (totalNum == curRoute.getCheckNum().intValue()) {
                                curRoute.setStatus(4);
                            } else {
                                curRoute.setStatus(3);
                            }
                            curRoute.setRouteDate(currentDate);
                            flowMapper.updateRouteCheck(curRoute);
                            FlowRoute next = flowMapper.findNextRoute(curRoute);
                            //获取最后一道序
                            FlowRoute lastRoute = getLastRoute(curRoute);
                            if (null != next && "转储".equals(next.getRoute())) {
                                trans.setStatus(3);
                                next.setRecNum(next.getRecNum() + trans.getNum());

                                if (totalNum == next.getRecNum()) {
                                    next.setStatus(4);
                                } else {
                                    next.setStatus(3);
                                    //检测改生产令全部最后一道序是否全部完成或未完成修改生产任务表的生产状态
                                }
                                flowMapper.updateRouteRecNum(next);
                                next.setRouteDate(currentDate);
                                flowMapper.updateRouteRouteDate(next);
                                //获取对应的库存信息如果没有则插入数据库，有则更新数量
                                //执行入库
                                HalfStore store = new HalfStore();
                                store.setSheetId(sheet.getId());
                                store.setNum(trans.getNum());
                                BeanUtil.copy(sheet, store);
                                store.setStoreAddr(trans.getApplyDept());
                                //生成入库记录
                                AsseHalfStoreRecord record = new AsseHalfStoreRecord();
                                //根据 生产令编号 部分 专业 图号 获取对应的库存
                                HalfStore existHalfStore = flowMapper.getExistHalfStore(store);
                                if (existHalfStore != null) {
                                    existHalfStore.setNum(existHalfStore.getNum() + trans.getNum());
                                    if (existHalfStore.getNum() <= existHalfStore.getDrawNum()) {
                                        flowMapper.updateHalfStoreNumByPrimary(existHalfStore);
                                        record.setStoreId(existHalfStore.getId());
                                    } else {
                                        Exception exception = new Exception();
                                        exception.printStackTrace();
                                    }
                                } else {
                                    flowMapper.insertHalfStore(store);
                                    record.setStoreId(store.getId());
                                }
                                record.setProdNo(sheet.getProdNo());
                                record.setSpecial(sheet.getSpecial());
                                record.setPartId(sheet.getPartId());
                                record.setDrawName(sheet.getDrawName());
                                record.setDrawNo(sheet.getDrawNo());
                                record.setDrawNum(trans.getNum());
                                record.setWeight(sheet.getWeight());
                                record.setQuality(sheet.getQuality());
                                record.setSpec(sheet.getSpec());
                                record.setStoreType(1);
                                record.setRecordType(1);
                                record.setStoreAddr(trans.getApplyDept());
                                record.setStorageRegisterCode(trans.getApplyCode());
                                record.setStorageTime(currentDate);
                                flowMapper.insertAsseHalfStoreRecord(record);
                                trans.setRecordId(record.getId());
                                flowMapper.updateSheetTrans(trans);
                            }
                            //如果最后道序是铆焊则根据接收数量判断把状态进行更改，部分接收是3，完全接收是4
                            else if (next.getRoute().equals("参焊") && lastRoute.getRoute().equals("参焊") && lastRoute.getOrderNo() == next.getOrderNo()) {
                                trans.setStatus(3);
                                //获取零件总数
                                FlowRoute totalNumRoute = flowMapper.getFirstRoute(curRoute);
                                next.setRecNum(next.getRecNum() + trans.getNum());
                                next.setMayApplyNum(0);
                                if (totalNumRoute.getRecNum().intValue() > next.getRecNum().intValue()) {
                                    next.setStatus(3);
                                } else {
                                    next.setStatus(4);
                                }
                                flowMapper.updateRouteRecNum(next);
                            }
                            //如果该序全部转序则修改对应任务的状态
                            if (curRoute.getRoute().equals("铆焊") || curRoute.getRoute().equals("机加")) {
                                int routeCount = flowMapper.getRoteCountBySheetId(curRoute.getRoute(), sheet.getProdNo());
                                int routeCompleteCount = flowMapper.getRoteCompleteCountBySheetId(curRoute.getRoute(), sheet.getProdNo());
                                Date start = currentDate;
                                Date end = currentDate;
                                if (routeCount == routeCompleteCount) {
                                    String tasCod = "";
                                    if (curRoute.getRoute().equals("铆焊")) {
                                        tasCod = "t11";
                                    } else if (curRoute.getRoute().equals("机加")) {
                                        tasCod = "t14";
                                    }
                                    flowMapper.updateTaskStatusAndEndDat(sheet.getProdNo(), tasCod, end, u.getDeptId(), u.getId());
                                } else {
                                    String tasCod = "";
                                    if (curRoute.getRoute().equals("铆焊")) {
                                        tasCod = "t11";
                                    } else if (curRoute.getRoute().equals("机加")) {
                                        tasCod = "t14";
                                    }
                                    Date dataBaseStartDate = flowMapper.getDataBaseStartDate(sheet.getProdNo(), tasCod);
                                    if (dataBaseStartDate == null) {
                                        flowMapper.updateTaskStatusAndStartDat(sheet.getProdNo(), tasCod, start, u.getDeptId(), u.getId());
                                    }
                                }
                            }
                            //flowMapper.updateCheckTrans(trans);
                            //检测改生产令全部最后一道序是否全部完成或未完成修改生产任务表的生产状态
                            checkLastRouteIsFinished(sheet);
                        } else {
                            return 1;
                        }
                    } else if (curProcess.getStatus().intValue() == 3) {
                        //获取最后一道工序
                        FlowProcess lastProcess = flowMapper.getLastProcess(curProcess);
                        //用来判断本工序是否是该路线的最后一序,如果是最后一道工序
                        if (curProcess.getProcess().equals(lastProcess.getProcess()) && curProcess.getOrderNum().intValue() == lastProcess.getOrderNum().intValue()) {
                            //更新本路线信息
                            int totalRouteNum = sheet.getDrawNum() - sheet.getInvalid();
                            curRoute.setCheckNum(curProcess.getCheckNum());
                            curRoute.setCanChange(2);
                            if (totalNum == curRoute.getCheckNum().intValue()) {
                                curRoute.setStatus(4);
                            } else {
                                curRoute.setStatus(3);
                            }
                            curRoute.setRouteDate(currentDate);
                            flowMapper.updateRouteCheck(curRoute);
                            FlowRoute next = flowMapper.findNextRoute(curRoute);
                            //获取最后一道序
                            FlowRoute lastRoute = getLastRoute(curRoute);
                            if (null != next && "转储".equals(next.getRoute())) {
                                trans.setStatus(3);
                                next.setRecNum(next.getRecNum() + trans.getNum());
                                if (totalNum == next.getRecNum()) {
                                    next.setStatus(4);
                                } else {
                                    next.setStatus(3);
                                    //检测改生产令全部最后一道序是否全部完成或未完成修改生产任务表的生产状态
                                }
                                flowMapper.updateRouteRecNum(next);
                                next.setRouteDate(currentDate);
                                flowMapper.updateRouteRouteDate(next);
                                //获取对应的库存信息如果没有则插入数据库，有则更新数量
                                //执行入库
                                HalfStore store = new HalfStore();
                                store.setSheetId(sheet.getId());
                                store.setNum(trans.getNum());
                                BeanUtil.copy(sheet, store);
                                store.setStoreAddr(trans.getApplyDept());
                                //生成入库记录
                                AsseHalfStoreRecord record = new AsseHalfStoreRecord();
                                //根据 生产令编号 部分 专业 图号 获取对应的库存
                                HalfStore existHalfStore = flowMapper.getExistHalfStore(store);
                                if (existHalfStore != null) {
                                    existHalfStore.setNum(existHalfStore.getNum() + trans.getNum());
                                    if (existHalfStore.getNum() <= existHalfStore.getDrawNum()) {
                                        flowMapper.updateHalfStoreNumByPrimary(existHalfStore);
                                        record.setStoreId(existHalfStore.getId());
                                    } else {
                                        Exception exception = new Exception();
                                        exception.printStackTrace();
                                    }
                                } else {
                                    flowMapper.insertHalfStore(store);
                                    record.setStoreId(store.getId());
                                }
                                record.setProdNo(sheet.getProdNo());
                                record.setSpecial(sheet.getSpecial());
                                record.setPartId(sheet.getPartId());
                                record.setDrawName(sheet.getDrawName());
                                record.setDrawNo(sheet.getDrawNo());
                                record.setDrawNum(trans.getNum());
                                record.setWeight(sheet.getWeight());
                                record.setQuality(sheet.getQuality());
                                record.setSpec(sheet.getSpec());
                                record.setStoreType(1);
                                record.setRecordType(1);
                                record.setStoreAddr(trans.getApplyDept());
                                record.setStorageRegisterCode(trans.getApplyCode());
                                record.setStorageTime(currentDate);
                                flowMapper.insertAsseHalfStoreRecord(record);
                                trans.setRecordId(record.getId());
                                flowMapper.updateSheetTrans(trans);
                            }
                            //如果最后道序是铆焊则根据接收数量判断把状态进行更改，部分接收是3，完全接收是4
                            else if (next.getRoute().equals("参焊") && lastRoute.getRoute().equals("参焊") && lastRoute.getOrderNo() == next.getOrderNo()) {
                                trans.setStatus(3);
                                //获取零件总数
                                FlowRoute totalNumRoute = flowMapper.getFirstRoute(curRoute);
                                next.setRecNum(next.getRecNum() + trans.getNum());
                                next.setMayApplyNum(0);
                                if (totalNumRoute.getRecNum().intValue() > next.getRecNum().intValue()) {
                                    next.setStatus(3);
                                } else {
                                    next.setStatus(4);
                                }
                                flowMapper.updateRouteRecNum(next);
                            }
                            //如果该序全部转序则修改对应任务的状态
                            if (curRoute.getRoute().equals("铆焊") || curRoute.getRoute().equals("机加")) {
                                int routeCount = flowMapper.getRoteCountBySheetId(curRoute.getRoute(), sheet.getProdNo());
                                int routeCompleteCount = flowMapper.getRoteCompleteCountBySheetId(curRoute.getRoute(), sheet.getProdNo());
                                Date start = currentDate;
                                Date end = currentDate;
                                if (routeCount == routeCompleteCount) {
                                    String tasCod = "";
                                    if (curRoute.getRoute().equals("铆焊")) {
                                        tasCod = "t11";
                                    } else if (curRoute.getRoute().equals("机加")) {
                                        tasCod = "t14";
                                    }
                                    flowMapper.updateTaskStatusAndEndDat(sheet.getProdNo(), tasCod, end, u.getDeptId(), u.getId());
                                } else {
                                    String tasCod = "";
                                    if (curRoute.getRoute().equals("铆焊")) {
                                        tasCod = "t11";
                                    } else if (curRoute.getRoute().equals("机加")) {
                                        tasCod = "t14";
                                    }
                                    Date dataBaseStartDate = flowMapper.getDataBaseStartDate(sheet.getProdNo(), tasCod);
                                    if (dataBaseStartDate == null) {
                                        flowMapper.updateTaskStatusAndStartDat(sheet.getProdNo(), tasCod, start, u.getDeptId(), u.getId());
                                    }
                                }
                            }
                            //flowMapper.updateCheckTrans(trans);
                            //检测改生产令全部最后一道序是否全部完成或未完成修改生产任务表的生产状态
                            checkLastRouteIsFinished(sheet);
                        } else {
                            return 1;
                        }
                    }
                }

            }
        }
        //如果是装配转序
        else if (trans.getType().intValue() == 2) {
            FlowRoute cur = flowMapper.findCurRoute(trans);
            if (cur.getApplyNum() >= cur.getCheckNum()) {
                if (dbCheck != null) {
                    check.setId(dbCheck.getId());
                    operationResult = flowMapper.updateFlowCheckForSuccessByPrimaryKey(check);
                } else {
                    operationResult = flowMapper.insertFlowCheckForSuccessByPrimaryKey(check);
                }
                FlowRoute next = flowMapper.findNextRoute(cur);
                FlowSheet sheet = flowMapper.getSheet(cur);
                int totalNum = sheet.getDrawNum();
                cur.setCheckNum(cur.getCheckNum() + trans.getNum());
                if (totalNum == cur.getCheckNum().intValue()) {
                    cur.setStatus(4);
                } else {
                    cur.setStatus(3);
                }
                if ("转储".equals(next.getRoute())) {
                    //修改倒数第二道序为已接收
                    trans.setStatus(3);
                    //修改最后一道序的接收数量和状态
                    next.setRecNum(next.getRecNum() + trans.getNum());
                    if (next.getRecNum() == totalNum) {
                        next.setStatus(4);
                    } else {
                        next.setStatus(3);
                    }
                    flowMapper.updateRouteRecNum(next);

                    // 判断 库存记录是否已经存在，存在更新，不存在插入（保证装配派工单与）
                    AssemblyStore asseStore = flowMapper.findStoreBySheetId(sheet.getId());
                    AssemblyStore store = new AssemblyStore();
                    // 插入成品库
                    if (asseStore != null) {
                        BeanUtil.copy(asseStore, store);
                        store.setSheetId(sheet.getId());
                        store.setDrawNum(asseStore.getDrawNum() + trans.getNum());
                        store.setStoreAddr(trans.getApplyDept());
                        flowMapper.updateStore(store);
                    } else {
                        BeanUtil.copy(sheet, store);
                        store.setSheetId(sheet.getId());
                        store.setDrawNum(trans.getNum());
                        store.setStoreAddr(trans.getApplyDept());
                        store.setId(null);
                        flowMapper.insertStore(store);
                    }

                    // 生产装配件入库记录
                    AssemblyStoreRecord storeRecord = new AssemblyStoreRecord();
                    storeRecord.setProdNo(store.getProdNo());
                    storeRecord.setSpecial(store.getSpecial());
                    storeRecord.setPartId(store.getPartId());
                    storeRecord.setDrawName(store.getDrawName());
                    storeRecord.setDrawNo(store.getDrawNo());
                    storeRecord.setWeight(store.getDrawWeight());
                    storeRecord.setDrawNum(trans.getNum());
                    storeRecord.setStoreType(1);
                    storeRecord.setRecordType(1);
                    storeRecord.setStoreAddr(store.getStoreAddr());
                    storeRecord.setStorageRegisterCode(trans.getApplyCode());
                    storeRecord.setStorageTime(new Date());
                    storeRecord.setCheckOpinion(trans.getResult());
                    storeRecord.setRemark(null);
                    storeRecord.setReplaceId(null);
                    storeRecord.setAsseStoreId(store.getId());
                    flowMapper.insertStoreRecord(storeRecord);
                    // 转序单记录出入库记录主键，冲单时使用
                    trans.setRecordId(storeRecord.getId());
                    flowMapper.updateSheetTrans(trans);
                }
                cur.setRouteDate(new Date());// 最终转序时间
                cur.setCanChange(2);
                flowMapper.updateRouteCheck(cur);
                //flowMapper.updateCheckTrans(check);

                /**20210608 会议讨论 会议人员：徐一贺、陈欣、李青雨、马超、王松刚
                 * 1.如果生产令下所有工艺卡都已经装配完成时，回写生产令任务装配状态为已完成
                 * 2.如果生产令下生产、装配、安装任务都完成时，回写生产令生产完成状态及完成时间
                 * **/
                if ("转储".equals(next.getRoute()) && next.getStatus().compareTo(4) == 0) {
                    // 取得机械和流体未完成工艺卡装配数
                    int jlCount = flowMapper.getJxLtNotTranCompCount(sheet.getProdNo(), sheet.getId());
                    if (jlCount == 0) {
                        // 更新生产令装配任务状态
                        ProdTasStatus prodTas = new ProdTasStatus();
                        prodTas.setProdNo(sheet.getProdNo());
                        prodTas.setProtSta(3);//任务状态：1=未开始，2=执行中，3=已完成
                        prodTas.setProtDat(new Date());// 状态反写时间
                        prodTas.setProtDepId(u.getBranchId());// 状态反写部门
                        prodTas.setProtEndDat(new Date());// 结束时间
                        flowMapper.updateProdTasProtStaByProdNo(prodTas);
                        // 更新生产令生产完成状态及时间
                        udpCodStaAndDate(sheet.getProdNo(), 2);
                    } else {
                        // 更新生产令装配任务开始时间及状态
                        ProdTasStatus prodTas = new ProdTasStatus();
                        prodTas.setProdNo(sheet.getProdNo());
                        prodTas.setProtSta(2);//任务状态：1=未开始，2=执行中，3=已完成
                        prodTas.setProtDat(new Date());// 状态反写时间
                        prodTas.setProtDepId(u.getBranchId());// 状态反写部门
                        prodTas.setProtStaDat(new Date());// 开始时间
                        flowMapper.updateProdTasStartProtStaByProdNo(prodTas);
                    }
                } else {
                    // 更新生产令装配任务开始时间及状态
                    ProdTasStatus prodTas = new ProdTasStatus();
                    prodTas.setProdNo(sheet.getProdNo());
                    prodTas.setProtSta(2);//任务状态：1=未开始，2=执行中，3=已完成
                    prodTas.setProtDat(new Date());// 状态反写时间
                    prodTas.setProtDepId(u.getBranchId());// 状态反写部门
                    prodTas.setProtStaDat(new Date());// 开始时间
                    flowMapper.updateProdTasStartProtStaByProdNo(prodTas);
                }
            } else {
                return 1;
            }

        }
        //如果是返修
        else if (trans.getType().intValue() == 3) {
            if (dbCheck != null) {
                check.setId(dbCheck.getId());
                operationResult = flowMapper.updateFlowCheckForSuccessByPrimaryKey(check);
            } else {
                operationResult = flowMapper.insertFlowCheckForSuccessByPrimaryKey(check);
            }
        }
        return 1;
    }

    /**
     * @param prodNo 生产令编号
     * @param type   调用源头：1=生产，2=装配，3=安装
     * @Author wsg
     * @Date 13:29 2021/6/8
     * @Description 更新生产令生产完成状态及时间
     **/
    public Integer udpCodStaAndDate(String prodNo, Integer type) {
        Integer status = 0;// 0=未完成，1=已完成
        Date comDat = null;// 完成时间
        ProdTasStatus tasStatus = flowMapper.getProdTasStatusByProdNo(prodNo);
        if (type.compareTo(1) == 0 && tasStatus != null && (tasStatus.getAssSta().compareTo(3) == 0 || tasStatus.getAssSta().compareTo(0) == 0) && (tasStatus.getInsSta().compareTo(3) == 0 || tasStatus.getInsSta().compareTo(0) == 0)) {
            // 生产
            status = 1;
            comDat = new Date();
        } else if (type.compareTo(2) == 0 && tasStatus != null && (tasStatus.getProdSta().compareTo(3) == 0 || tasStatus.getProdSta().compareTo(0) == 0) && (tasStatus.getInsSta().compareTo(3) == 0 || tasStatus.getInsSta().compareTo(0) == 0)) {
            // 装配
            status = 1;
            comDat = new Date();
        } else if (type.compareTo(3) == 0 && tasStatus != null && (tasStatus.getProdSta().compareTo(3) == 0 || tasStatus.getProdSta().compareTo(0) == 0) && (tasStatus.getAssSta().compareTo(3) == 0 || tasStatus.getAssSta().compareTo(0) == 0)) {
            // 安装
            status = 1;
            comDat = new Date();
        }
        return flowMapper.udpCodStaAndDate(prodNo, status, comDat);
//        return flowMapper.updateProjectInfoStatus(prodNo, status, comDat);
    }

    /**
     * 检测最后一道序是否转序完毕如果转序完毕则生产任务完成，如果未完成则是执行中
     */
    @Transactional(rollbackFor = Exception.class)
    void checkLastRouteIsFinished(FlowSheet sheet) {
        User u = (User) ServletUtils.getSession().getAttribute("user");
        //获取总数量
        int totalCount = flowMapper.getLastRouteTotalCount(sheet);
        //获取完成总数量
        int totalFinishedCount = flowMapper.getLastRouteTotalFinishedCount(sheet);
        if (totalCount == totalFinishedCount) {
            flowMapper.updateTaskStatusAndEndDat(sheet.getProdNo(), "t27", new Date(), u.getDeptId(), u.getId());
            flowMapper.updateReturnEndDate(sheet.getProdNo(), "r11", new Date(), u.getDeptId(), u.getId());
            assemblyService.udpCodStaAndDate(sheet.getProdNo(), 1);
        } else {
            flowMapper.updateTaskStatusAndStartDat(sheet.getProdNo(), "t27", new Date(), u.getDeptId(), u.getId());
        }
    }


    /**
     * 接收
     */
    @Transactional(rollbackFor = Exception.class)
    public int rec(FlowTrans trans) {
        trans = flowMapper.getTrans(trans.getId());
        if (trans.getStatus() != 2) {
            return 0;
        }
        User u = (User) ServletUtils.getSession().getAttribute("user");
        u = flowMapper.getUserById(u.getId());
        //如果是制作工艺卡
        if (trans.getType() == 1) {
            //如果是厂级转序
            if (trans.getTransMode().intValue() == 1) {
                trans.setRecCode(u.getAccount());
                trans.setRecName(u.getName());
                trans.setRecTime(new Date());
                trans.setRecDept(u.getBranch());
                trans.setStatus(3);
                flowMapper.updateRecTrans(trans);
                //获取当前路线
                FlowRoute cur = flowMapper.findCurRoute(trans);
                //获取下一道序
                FlowRoute nextRoute = flowMapper.getNextRoute(cur);
                //获取零件总数
                FlowRoute totalNum = flowMapper.getFirstRoute(cur);
                //获取最后一道序
                FlowRoute lastRoute = getLastRoute(cur);
                //如果最后道序是参焊则根据接收数量判断把状态进行更改，部分接收是3，完全接收是4
                if (nextRoute.getRoute().equals("参焊") && lastRoute.getRoute().equals("参焊") && lastRoute.getOrderNo() == nextRoute.getOrderNo()) {
                    nextRoute.setRecNum(nextRoute.getRecNum() + trans.getNum());
                    nextRoute.setMayApplyNum(0);
                    if (totalNum.getRecNum().intValue() > nextRoute.getRecNum().intValue()) {
                        nextRoute.setStatus(3);
                    } else {
                        nextRoute.setStatus(4);
                    }
                    flowMapper.updateRouteRecNum(nextRoute);
                    nextRoute.setCanChange(2);
                    flowMapper.updateFlowRouteCanChangeByPrimaryKey(nextRoute);
                }
                //非最后一道序则正常进行下下一道序修改成执行中
                else {
                    FlowRoute route = flowMapper.findNextRoute(cur);
                    route.setRecNum(route.getRecNum() + trans.getNum());
                    route.setMayApplyNum(route.getMayApplyNum() + trans.getNum());
                    route.setStatus(2);
                    flowMapper.updateRouteRecNum(route);
                    route.setCanChange(2);
                    flowMapper.updateFlowRouteCanChangeByPrimaryKey(route);
                    //如果下个路线是车间级转序
                    if (route.getIsPlantLevelSt() == 0) {
                        //根据路线id和序号获取车间级转序（不包含删除）
                        FlowProcess process = flowMapper.getFlowProcessByRouteIdAndOrderNum(route.getId());
                        process.setRecNum(process.getRecNum() + trans.getNum());
                        process.setMayApplyNum(process.getMayApplyNum() + trans.getNum());
                        process.setStatus(2);
                        flowMapper.updateProcessRecNum(process);
                    }
                }
            }
            //如果是车间级转序
            else {
                trans.setRecCode(u.getAccount());
                trans.setRecName(u.getName());
                trans.setRecTime(new Date());
                trans.setRecDept(u.getBranch());
                trans.setStatus(3);
                flowMapper.updateRecTrans(trans);
                //获取当前工序
                FlowProcess curProcess = flowMapper.findCurProcess(trans);
                //获取该路线最后序的信息
                FlowProcess currentRouteLastProcess = flowMapper.getCurrentRouteLastProcess(curProcess);
                //如果该序工序是该路线的最后一道工序
                if (curProcess.getProcess().equals(currentRouteLastProcess.getProcess()) && curProcess.getOrderNum().intValue() == currentRouteLastProcess.getOrderNum().intValue()) {
                    //获取当前路线
                    FlowRoute cur = flowMapper.findCurRoute(trans);
                    //获取下一道序
                    FlowRoute nextRoute = flowMapper.getNextRoute(cur);
                    //获取零件总数
                    FlowRoute totalNum = flowMapper.getFirstRoute(cur);
                    //获取最后一道序
                    FlowRoute lastRoute = getLastRoute(cur);
                    //如果最后道序是参焊则根据接收数量判断把状态进行更改，部分接收是3，完全接收是4
                    if (nextRoute.getRoute().equals("参焊") && lastRoute.getRoute().equals("参焊") && lastRoute.getOrderNo() == nextRoute.getOrderNo()) {
                        nextRoute.setRecNum(nextRoute.getRecNum() + trans.getNum());
                        nextRoute.setMayApplyNum(0);
                        if (totalNum.getRecNum().intValue() > nextRoute.getRecNum().intValue()) {
                            nextRoute.setStatus(3);
                        } else {
                            nextRoute.setStatus(4);
                        }
                        flowMapper.updateRouteRecNum(nextRoute);
                    }
                    //非最后一道序则正常进行下下一道序修改成执行中
                    else {
                        FlowRoute route = flowMapper.findNextRoute(cur);
                        route.setRecNum(route.getRecNum() + trans.getNum());
                        route.setMayApplyNum(route.getMayApplyNum() + trans.getNum());
                        route.setStatus(2);
                        flowMapper.updateRouteRecNum(route);
                    }
                }
                //非最后一道工序
                else {
                    FlowProcess process = flowMapper.findNextProcess(curProcess);
                    process.setRecNum(process.getRecNum() + trans.getNum());
                    process.setMayApplyNum(process.getMayApplyNum() + trans.getNum());
                    process.setStatus(2);
                    flowMapper.updateProcessRecNum(process);
                }
            }
        }
        //如果是装配转序
        else if (trans.getType() == 2) {
            if (trans.getStatus() != 2) {
                return 0;
            }
            trans.setRecCode(u.getAccount());
            trans.setRecName(u.getName());
            trans.setRecTime(new Date());
            trans.setRecDept(u.getBranch());
            trans.setStatus(3);
            flowMapper.updateRecTrans(trans);
            FlowRoute cur = flowMapper.findCurRoute(trans);
            //获取下一道序
            FlowRoute next = flowMapper.findNextRoute(cur);
            next.setRecNum(next.getRecNum() + trans.getNum());
            next.setMayApplyNum(next.getMayApplyNum() + trans.getNum());
            next.setStatus(2);
            flowMapper.updateRouteRecNum(next);
        }
        //如果是返修转序
        else if (trans.getType() == 3) {
            if (trans.getStatus() != 2) {
                return 0;
            }
            trans.setRecCode(u.getAccount());
            trans.setRecName(u.getName());
            trans.setRecTime(new Date());
            trans.setRecDept(u.getBranch());
            trans.setStatus(3);
            flowMapper.updateRecTrans(trans);
        }
        return 1;
    }

    /**
     * @methodName: getLastRoute
     * @description: 获取最后一道序
     * @param: cur
     * @return： com.zw.transition.entity.FlowRoute
     * @exception：
     * @author： 徐一贺 tel:18341916590
     * @designer： 陈欣
     * @leader： 陈欣 tel:18104194240
     * @date： 2021/4/16 13:56
     * @office: 智能控制设计科
     * @research institute： 智能控制设计所
     * @department： 机械设计院
     * @company: 辽宁忠旺机械设备制造有限公司
     * @group： 忠旺集团
     * @version: 1.0
     */
    private FlowRoute getLastRoute(FlowRoute cur) {
        return flowMapper.getLastRoute(cur);
    }

    /**
     * 查询 清单
     */
    public FlowSheet findSheet(String code) {
        QrParse parse = getQrParse(code);
        if (parse == null) return null;
        FlowSheet sheet = flowMapper.findSheet(parse);
        return sheet;
    }

    /**
     * 历史申请
     */
    public List<FlowTrans> findHisApplyList(String prodNo, String drawNo) {
        User u = (User) ServletUtils.getSession().getAttribute("user");
        return flowMapper.findHisApplyList(u.getAccount(), prodNo, drawNo);
    }

    /**
     * 历史申请
     */
    public List<FlowTrans> findHisApplyListOld(String prodNo, String drawNo) {
        User u = (User) ServletUtils.getSession().getAttribute("user");
        return flowMapper.findHisApplyListOld(u.getAccount(), prodNo, drawNo);
    }

    public FlowTrans getHisApplyPrimaryKey(Integer id) {
        return flowMapper.getHisApplyPrimaryKey(id);
    }

    /**
     * 历史接收
     */
    public List<FlowTrans> findHisRecList(String prodNo, String drawNo) {
        User u = (User) ServletUtils.getSession().getAttribute("user");
        return flowMapper.findHisRecList(u.getAccount(), prodNo, drawNo);
    }

    /**
     * 历史接收
     */
    public List<FlowTrans> findHisRecListOld(String prodNo, String drawNo) {
        User u = (User) ServletUtils.getSession().getAttribute("user");
        return flowMapper.findHisRecListOld(u.getAccount(), prodNo, drawNo);
    }

    /**
     * 历史接收
     */
    public FlowTrans getHisRecByTransId(Integer id) {
        return flowMapper.getHisRecByTransId(id);
    }

    /**
     * 历史质检
     */
    public List<FlowTrans> findHisCheckList(String prodNo, String drawNo) {
        User u = (User) ServletUtils.getSession().getAttribute("user");
        return flowMapper.findHisCheckList(u.getAccount(), prodNo, drawNo);
    }

    /**
     * 历史质检
     */
    public List<FlowTrans> findHisCheckListOld(String prodNo, String drawNo) {
        User u = (User) ServletUtils.getSession().getAttribute("user");
        return flowMapper.findHisCheckListOld(u.getAccount(), prodNo, drawNo);
    }

    /**
     * 历史质检
     */
    public FlowTrans getHisCheckByTransId(Integer id) {
        return flowMapper.getHisCheckByTransId(id);
    }

    /**
     * 二维码解析
     */
    private QrParse getQrParse(String code) {
        String[] arr = code.split("\\|");
        if (arr == null || arr.length < 4) {
            return null;
        }
        QrParse parse = new QrParse();
        parse.setProNo(arr[0]);
        parse.setDrawNo(arr[1]);
        parse.setPartId(arr[2]);
        parse.setCategory(arr[3]);
        return parse;
    }

    /**
     * 重新申请质检
     */
    public int repeatApply(Integer id) {
        return flowMapper.updateTransStatus(id, 1);
    }

    /**
     * 删除质检申请
     */
    @Transactional(rollbackFor = Exception.class)
    public int delApply(Integer id) {
        FlowTrans trans = flowMapper.getTrans(id);
        if (trans.getIsDel() == 1) {
            return 0;
        }
        if (trans.getType().intValue() != 3) {
            if (trans.getTransMode().intValue() == 1) {
                flowMapper.updateTransIsdel(id, 1);
                FlowRoute route = flowMapper.findCurRoute(trans);
                route.setApplyNum(trans.getNum());
                return flowMapper.updateRouteDel(route);
            } else if (trans.getTransMode().intValue() == 2) {
                flowMapper.updateTransIsdel(id, 1);
                FlowRoute route = flowMapper.findCurRoute(trans);
                FlowProcess process = flowMapper.getFlowProcessByRouteIdAndProcessAndOrderNum(route.getId(), trans.getProcess(), trans.getOrderNum());
                process.setApplyNum(trans.getNum());
                return flowMapper.updateProcessDel(process);
            }
        }
        return flowMapper.updateTransIsdel(id, 1);
    }

    /**
     * 取消接收
     */
    @Transactional(rollbackFor = Exception.class)
    public int cancelRec(FlowTrans trans) throws Exception {
        trans = flowMapper.getTrans(trans.getId());
        if (trans.getStatus() != 3) {
            return 0;
        }
        User u = (User) ServletUtils.getSession().getAttribute("user");
        trans.setRecCode(null);
        trans.setRecName(null);
        trans.setRecTime(null);
        trans.setStatus(2);
        flowMapper.updateRecTrans(trans);
        //如果是制作件工艺卡
        if (trans.getType() == 1) {
            //如果是厂级转序
            if (trans.getTransMode().intValue() == 1) {
                //当前路线
                FlowRoute curuetRoute = flowMapper.findCurRoute(trans);
                //下一级路线
                FlowRoute nextRoute = flowMapper.findNextRoute(curuetRoute);
                if(nextRoute.getRecNum() - trans.getNum() < 0 && nextRoute.getMayApplyNum() - trans.getNum() != nextRoute.getRecNum() - trans.getNum())
                {
                    throw new Exception();
                }
                nextRoute.setRecNum(nextRoute.getRecNum() - trans.getNum());
                nextRoute.setMayApplyNum(nextRoute.getMayApplyNum() - trans.getNum());
                if (nextRoute.getRecNum().intValue() == 0) {
                    nextRoute.setStatus(1);
                }
                flowMapper.updateRouteRecNum(nextRoute);
                //如果下一序是车间级转序
                if (nextRoute.getIsPlantLevelSt().intValue() == 0) {
                    //获取下一序的头一个工序
                    FlowProcess curentProcess = flowMapper.findCurRouteFirstProcess(nextRoute);
                    curentProcess.setRecNum(curentProcess.getRecNum() - trans.getNum());
                    curentProcess.setMayApplyNum(curentProcess.getMayApplyNum() - trans.getNum());
                    if (curentProcess.getRecNum().intValue() == 0) {
                        curentProcess.setStatus(1);
                    }
                    flowMapper.updateProcessRecNum(curentProcess);
                }
            }
            //如果是车间级转序
            else {
                //当前工序
                FlowProcess curentProcess = flowMapper.findCurProcess(trans);
                //获取当前路线最后一道工序
                FlowProcess lastProcess = flowMapper.getCurrentRouteLastProcess(curentProcess);
                //下一级工序
                FlowProcess nextProcess = flowMapper.findNextProcess(curentProcess);
                if (lastProcess.getProcess().equals(curentProcess.getProcess()) && lastProcess.getOrderNum().intValue() == curentProcess.getOrderNum().intValue()) {
                    //当前路线
                    FlowRoute curuetRoute = flowMapper.findCurRoute(trans);
                    //下一级路线
                    FlowRoute nextRoute = flowMapper.findNextRoute(curuetRoute);
                    if(nextRoute.getRecNum() - trans.getNum() < 0 && nextRoute.getMayApplyNum() - trans.getNum() != nextRoute.getRecNum() - trans.getNum())
                    {
                        throw new Exception();
                    }
                    nextRoute.setRecNum(nextRoute.getRecNum() - trans.getNum());
                    nextRoute.setMayApplyNum(nextRoute.getMayApplyNum() - trans.getNum());
                    if (nextRoute.getRecNum().intValue() == 0) {
                        nextRoute.setStatus(1);
                    }
                    flowMapper.updateRouteRecNum(nextRoute);
                    //如果下一序是车间级转序
                    if (nextRoute.getIsPlantLevelSt().intValue() == 0) {
                        //获取下一序的头一个工序
                        FlowProcess curentProcess1 = flowMapper.findCurRouteFirstProcess(nextRoute);
                        curentProcess1.setRecNum(curentProcess1.getRecNum() - trans.getNum());
                        curentProcess1.setMayApplyNum(curentProcess1.getMayApplyNum() - trans.getNum());
                        if (curentProcess1.getRecNum().intValue() == 0) {
                            curentProcess1.setStatus(1);
                        }
                        flowMapper.updateProcessRecNum(curentProcess1);
                    }
                } else {
                    if (nextProcess != null) {
                        nextProcess.setRecNum(nextProcess.getRecNum() - trans.getNum());
                        nextProcess.setMayApplyNum(nextProcess.getMayApplyNum() - trans.getNum());
                        if (nextProcess.getRecNum().intValue() == 0) {
                            nextProcess.setStatus(1);
                        }
                        flowMapper.updateProcessRecNum(nextProcess);
                    }
                }
            }
        }
        //如果是装配转序
        else if (trans.getType() == 2) {
            trans.setRecCode(null);
            trans.setRecName(null);
            trans.setRecTime(null);
            trans.setRecDept(null);
            trans.setStatus(2);
            flowMapper.updateRecTrans(trans);
            //当前路线
            FlowRoute curuetRoute = flowMapper.findCurRoute(trans);
            //下一级路线
            FlowRoute nextRoute = flowMapper.findNextRoute(curuetRoute);
            if(nextRoute.getRecNum() - trans.getNum() < 0 && nextRoute.getMayApplyNum() - trans.getNum() != nextRoute.getRecNum() - trans.getNum())
            {
                throw new Exception();
            }
            nextRoute.setRecNum(nextRoute.getRecNum() - trans.getNum());
            nextRoute.setMayApplyNum(nextRoute.getMayApplyNum() - trans.getNum());
            if (nextRoute.getRecNum().intValue() == 0) {
                nextRoute.setStatus(1);
            }
            flowMapper.updateRouteRecNum(nextRoute);
        }
        //如果是返修艺卡
        else if (trans.getType() == 3) {
            trans.setRecCode(null);
            trans.setRecName(null);
            trans.setRecTime(null);
            trans.setRecDept(null);
            trans.setStatus(2);
            flowMapper.updateRecTrans(trans);
        }
        return 1;
    }


    /**
     * 取消质检
     */
    public int cancelCheck(FlowTrans trans) {
        FlowTrans t = flowMapper.getTrans(trans.getId());
        if (t.getStatus() == 1) {
            return 0;
        }
        User currentUser = (User) ServletUtils.getSession().getAttribute("user");
        //如果是返修转序
        if (t.getType() == 3) {
            //删除质检数据
            //1.删除质检附件表数据
            FlowCheckAttachments deleteUpdateCheckAttachmentsObj = new FlowCheckAttachments();
            FlowCheck flowCheck = flowMapper.getFlowCheckByTransId(t.getId());
            deleteUpdateCheckAttachmentsObj.setCheckId(flowCheck.getId());
            deleteUpdateCheckAttachmentsObj.setDeleteCode(currentUser.getAccount());
            deleteUpdateCheckAttachmentsObj.setDeleteName(currentUser.getName());
            if (currentUser.getBranchName() != null) {
                deleteUpdateCheckAttachmentsObj.setDeleteDept(currentUser.getBranchName());
            }
            deleteUpdateCheckAttachmentsObj.setDeleteTime(new Date());
            deleteUpdateCheckAttachmentsObj.setIsDel(1);
            flowMapper.updateCheckAttachmentsByDelete(deleteUpdateCheckAttachmentsObj);
            //获取被删除的质检附件数据删除对应的附件
            List<FlowCheckAttachments> flowCheckAttachmentsList = flowMapper.findFlowCheckAttachmentsByRemove();
            //循环删除文件
            for (int i = 0; i < flowCheckAttachmentsList.size(); i++) {
                String afterPath = "checkOrder/" + flowCheck.getId() + "/";
                String allPath = uploadPath + afterPath;
                File file = new File(allPath + flowCheckAttachmentsList.get(i).getAttFileName());
                if (file.exists()) {
                    file.delete();
                }
            }
            //2.删除质检表数据
            flowMapper.updateFlowCheckByByDelete(flowCheck);
            t.setStatus(1);
            flowMapper.updateFlowTransStatusByPrimaryKey(t);
        } else {
            FlowRoute cur = flowMapper.findCurRoute(t);
            FlowSheet sheet = flowMapper.getSheet(cur);
            boolean isPass = true;
            //如果是制作工艺卡
            if (t.getType() == 1) {
                //厂级
                if (t.getTransMode() == 1) {
                    switch (t.getStatus()) {
                        case 5: // 作废
                            sheet.setInvalid(sheet.getInvalid() - t.getNum());
                            flowMapper.updateSheetInvalid(sheet);
                            break;
                        case 4: // 正常驳回
                            break;
                        case 3: // 倒数第二序
                            FlowRoute next = flowMapper.findNextRoute(cur);
                            if ("转储".equals(next.getRoute())) {
                                //获取对应的入库记录
                                AsseHalfStoreRecord record = flowMapper.getAsseHalfStoreRecordByPrimaryKey(t.getRecordId());
                                //获取对应的库存
                                HalfStore halfStore = flowMapper.getHalfStore(record);
                                //如果
                                if (halfStore.getNum() < record.getDrawNum()) {
                                    isPass = false;
                                    break;
                                } else {
                                    next.setRecNum(0);
                                    next.setMayApplyNum(0);
                                    next.setStatus(1);
                                    flowMapper.updateRouteRecNum(next);
                                    //生成对应的退库记录
                                    AsseHalfStoreRecord returnStoreRecord = record;
                                    returnStoreRecord.setRecordType(2);
                                    returnStoreRecord.setReplaceId(record.getId());
                                    returnStoreRecord.setStorageTime(new Date());
                                    flowMapper.insertAsseHalfStoreRecord(returnStoreRecord);
                                    halfStore.setNum(halfStore.getNum() - returnStoreRecord.getDrawNum());
                                    flowMapper.updateHalfStoreNumByPrimary(halfStore);
                                    t.setRecordId(null);
                                }
                            } else if ("参焊".equals(next.getRoute())) {
                                next.setRecNum(0);
                                next.setMayApplyNum(0);
                                next.setStatus(1);
                                next.setRouteDate(null);
                                flowMapper.updateRoute(next);
                            }
                            break;
                        case 2: // 正常质检
                            break;
                    }
                    cur.setCheckNum(cur.getCheckNum() - t.getNum());
                    cur.setStatus(2);
                    cur.setRouteDate(null);
                    cur.setCanChange(1);
                    flowMapper.updateRouteCheck(cur);
                    //因撤销质检更新转序单表数据
                    t.setStatus(1);
                    flowMapper.updateFlowTransByCancelCheck(t);
                    //删除质检数据
                    //1.删除质检附件表数据
                    FlowCheckAttachments deleteUpdateCheckAttachmentsObj = new FlowCheckAttachments();
                    FlowCheck flowCheck = flowMapper.getFlowCheckByTransId(t.getId());
                    deleteUpdateCheckAttachmentsObj.setCheckId(flowCheck.getId());
                    deleteUpdateCheckAttachmentsObj.setDeleteCode(currentUser.getAccount());
                    deleteUpdateCheckAttachmentsObj.setDeleteName(currentUser.getName());
                    if (currentUser.getBranchName() != null) {
                        deleteUpdateCheckAttachmentsObj.setDeleteDept(currentUser.getBranchName());
                    }
                    deleteUpdateCheckAttachmentsObj.setDeleteTime(new Date());
                    deleteUpdateCheckAttachmentsObj.setIsDel(1);
                    flowMapper.updateCheckAttachmentsByDelete(deleteUpdateCheckAttachmentsObj);
                    //获取被删除的质检附件数据删除对应的附件
                    List<FlowCheckAttachments> flowCheckAttachmentsList = flowMapper.findFlowCheckAttachmentsByRemove();
                    //循环删除文件
                    for (int i = 0; i < flowCheckAttachmentsList.size(); i++) {
                        String afterPath = "checkOrder/" + flowCheck.getId() + "/";
                        String allPath = uploadPath + afterPath;
                        File file = new File(allPath + flowCheckAttachmentsList.get(i).getAttFileName());
                        if (file.exists()) {
                            file.delete();
                        }
                    }
                    //2.删除质检表数据
                    flowMapper.updateFlowCheckByByDelete(flowCheck);
                    FlowRoute next = flowMapper.findNextRoute(cur);
                    if ("转储".equals(next.getRoute())) {
                        //获取对应的入库记录
                        AsseHalfStoreRecord record = flowMapper.getAsseHalfStoreRecordByPrimaryKey(t.getRecordId());
                        //获取对应的库存
                        HalfStore halfStore = flowMapper.getHalfStore(record);
                        //如果
                        next.setRecNum(0);
                        next.setMayApplyNum(0);
                        next.setStatus(1);
                        flowMapper.updateRouteRecNum(next);
                        //生成对应的退库记录
                        AsseHalfStoreRecord returnStoreRecord = record;
                        returnStoreRecord.setRecordType(2);
                        returnStoreRecord.setReplaceId(record.getId());
                        returnStoreRecord.setStorageTime(new Date());
                        flowMapper.insertAsseHalfStoreRecord(returnStoreRecord);
                        halfStore.setNum(halfStore.getNum() - returnStoreRecord.getDrawNum());
                        flowMapper.updateHalfStoreNumByPrimary(halfStore);
                        t.setRecordId(null);
                    } else if ("参焊".equals(next.getRoute())) {
                        next.setRecNum(0);
                        next.setMayApplyNum(0);
                        next.setStatus(1);
                        next.setRouteDate(null);
                        flowMapper.updateRoute(next);
                    }
                }
                //车间级
                else {
                    //获取当前工序
                    FlowProcess currentProcess = flowMapper.findCurProcess(t);
                    switch (t.getStatus()) {
                        case 5: // 作废
                            sheet.setInvalid(sheet.getInvalid() - t.getNum());
                            flowMapper.updateSheetInvalid(sheet);
                            break;
                        case 4: // 正常驳回
                            break;
                        case 3: // 倒数第二序
                            FlowRoute next = flowMapper.findNextRoute(cur);
                            if ("转储".equals(next.getRoute())) {
                                //获取对应的入库记录
                                AsseHalfStoreRecord record = flowMapper.getAsseHalfStoreRecordByPrimaryKey(t.getRecordId());
                                //获取对应的库存
                                HalfStore halfStore = flowMapper.getHalfStore(record);
                                //如果
                                if (halfStore.getNum() < record.getDrawNum()) {
                                    isPass = false;
                                    break;
                                } else {
                                    next.setRecNum(0);
                                    next.setMayApplyNum(0);
                                    next.setStatus(1);
                                    flowMapper.updateRouteRecNum(next);
                                    //生成对应的退库记录
                                    AsseHalfStoreRecord returnStoreRecord = record;
                                    returnStoreRecord.setRecordType(2);
                                    returnStoreRecord.setReplaceId(record.getId());
                                    returnStoreRecord.setStorageTime(new Date());
                                    flowMapper.insertAsseHalfStoreRecord(returnStoreRecord);
                                    halfStore.setNum(halfStore.getNum() - returnStoreRecord.getDrawNum());
                                    flowMapper.updateHalfStoreNumByPrimary(halfStore);
                                    t.setRecordId(null);
                                }
                            } else if ("参焊".equals(next.getRoute())) {
                                next.setRecNum(0);
                                next.setMayApplyNum(0);
                                next.setStatus(1);
                                next.setRouteDate(null);
                                flowMapper.updateRoute(next);
                            }
                            break;
                        case 2: // 正常质检
                            break;
                    }
                    currentProcess.setCheckNum(currentProcess.getCheckNum() - t.getNum());
                    currentProcess.setStatus(2);
                    currentProcess.setProcessDate(null);
                    flowMapper.updateProcessCheck(currentProcess);
                    //获取当前工序的路线最后一道工序
                    FlowProcess currentRoteLastProceee = flowMapper.getCurrentRouteLastProcess(currentProcess);
                    //如果当前工序是同路线的租后一道工序
                    if (currentRoteLastProceee.getOrderNum() == currentProcess.getOrderNum()) {
                        //获取当前路线    往回反写数量
                        FlowRoute currentProcessRoute = flowMapper.getFlowRouteByPrimaryKey(currentRoteLastProceee.getRouteId());
                        currentProcessRoute.setCheckNum(currentProcessRoute.getCheckNum() - t.getNum());
                        currentProcessRoute.setStatus(2);
                        currentProcessRoute.setRouteDate(null);
                        currentProcessRoute.setCanChange(1);
                        flowMapper.updateRouteCheck(currentProcessRoute);
                        //获取下一个路线
                        FlowRoute next = flowMapper.findNextRoute(cur);
                        if ("转储".equals(next.getRoute())) {
                            //获取对应的入库记录
                            AsseHalfStoreRecord record = flowMapper.getAsseHalfStoreRecordByPrimaryKey(t.getRecordId());
                            //获取对应的库存
                            HalfStore halfStore = flowMapper.getHalfStore(record);
                            //如果
                            if (halfStore.getNum() < record.getDrawNum()) {
                                isPass = false;
                            } else {
                                next.setRecNum(0);
                                next.setMayApplyNum(0);
                                next.setStatus(1);
                                flowMapper.updateRouteRecNum(next);
                                //生成对应的退库记录
                                AsseHalfStoreRecord returnStoreRecord = record;
                                returnStoreRecord.setRecordType(2);
                                returnStoreRecord.setReplaceId(record.getId());
                                returnStoreRecord.setStorageTime(new Date());
                                flowMapper.insertAsseHalfStoreRecord(returnStoreRecord);
                                halfStore.setNum(halfStore.getNum() - returnStoreRecord.getDrawNum());
                                flowMapper.updateHalfStoreNumByPrimary(halfStore);
                                t.setRecordId(null);
                            }
                        } else if ("参焊".equals(next.getRoute())) {
                            next.setRecNum(0);
                            next.setMayApplyNum(0);
                            next.setStatus(1);
                            next.setRouteDate(null);
                            flowMapper.updateRoute(next);
                        }
                    }
                    //因撤销质检更新转序单表数据
                    t.setStatus(1);
                    flowMapper.updateFlowTransByCancelCheck(t);
                    //删除质检数据
                    //1.删除质检附件表数据
                    FlowCheckAttachments deleteUpdateCheckAttachmentsObj = new FlowCheckAttachments();
                    FlowCheck flowCheck = flowMapper.getFlowCheckByTransId(t.getId());
                    deleteUpdateCheckAttachmentsObj.setCheckId(flowCheck.getId());
                    deleteUpdateCheckAttachmentsObj.setDeleteCode(currentUser.getAccount());
                    deleteUpdateCheckAttachmentsObj.setDeleteName(currentUser.getName());
                    if (currentUser.getBranchName() != null) {
                        deleteUpdateCheckAttachmentsObj.setDeleteDept(currentUser.getBranchName());
                    }
                    deleteUpdateCheckAttachmentsObj.setDeleteTime(new Date());
                    deleteUpdateCheckAttachmentsObj.setIsDel(1);
                    flowMapper.updateCheckAttachmentsByDelete(deleteUpdateCheckAttachmentsObj);
                    //获取被删除的质检附件数据删除对应的附件
                    List<FlowCheckAttachments> flowCheckAttachmentsList = flowMapper.findFlowCheckAttachmentsByRemove();
                    //循环删除文件
                    for (int i = 0; i < flowCheckAttachmentsList.size(); i++) {
                        String afterPath = "checkOrder/" + flowCheck.getId() + "/";
                        String allPath = uploadPath + afterPath;
                        File file = new File(allPath + flowCheckAttachmentsList.get(i).getAttFileName());
                        if (file.exists()) {
                            file.delete();
                        }
                    }
                    //2.删除质检表数据
                    flowMapper.updateFlowCheckByByDelete(flowCheck);

                }
            }
            //如果是装配转序
            else if (t.getType() == 2) {
                FlowRoute next = flowMapper.findNextRoute(cur);
                // 注：领导说暂无报废功能
                if (t.getStatus() == 1 || t.getStatus() == 4 || t.getStatus() == 5) {
                    return 0;
                }
                if (t.getStatus() == 3 && !next.getRoute().equals("转储")) {
                    return 0;
                }
                //删除质检数据
                //1.删除质检附件表数据
                FlowCheckAttachments deleteUpdateCheckAttachmentsObj = new FlowCheckAttachments();
                FlowCheck flowCheck = flowMapper.getFlowCheckByTransId(t.getId());
                deleteUpdateCheckAttachmentsObj.setCheckId(flowCheck.getId());
                deleteUpdateCheckAttachmentsObj.setDeleteCode(currentUser.getAccount());
                deleteUpdateCheckAttachmentsObj.setDeleteName(currentUser.getName());
                if (currentUser.getBranchName() != null) {
                    deleteUpdateCheckAttachmentsObj.setDeleteDept(currentUser.getBranchName());
                }
                deleteUpdateCheckAttachmentsObj.setDeleteTime(new Date());
                deleteUpdateCheckAttachmentsObj.setIsDel(1);
                flowMapper.updateCheckAttachmentsByDelete(deleteUpdateCheckAttachmentsObj);
                //获取被删除的质检附件数据删除对应的附件
                List<FlowCheckAttachments> flowCheckAttachmentsList = flowMapper.findFlowCheckAttachmentsByRemove();
                //循环删除文件
                for (int i = 0; i < flowCheckAttachmentsList.size(); i++) {
                    String afterPath = "checkOrder/" + flowCheck.getId() + "/";
                    String allPath = uploadPath + afterPath;
                    File file = new File(allPath + flowCheckAttachmentsList.get(i).getAttFileName());
                    if (file.exists()) {
                        file.delete();
                    }
                }

                //2.删除质检表数据
                flowMapper.updateFlowCheckByByDelete(flowCheck);
                FlowTrans befRecord = new FlowTrans();
                befRecord.setRecordId(t.getRecordId());
                t.setRecordId(null);
                // 回写 工序审核数量
                cur.setCheckNum(cur.getCheckNum() - t.getNum());
                cur.setStatus(2); // 工序执行中
                cur.setRouteDate(null);
                flowMapper.updateRouteCheck(cur);
                flowMapper.updateSheetTrans(t);
                t.setStatus(1);
                flowMapper.updateFlowTransByCancelCheck(t);
                // 判断 是否是最后工序，如果最后工序‘转储’时，要删除 asse_store 成品库 数据
                if ("转储".equals(next.getRoute())) {
                    next.setRecNum(0);
                    next.setStatus(1);
                    flowMapper.updateRouteRecNum(next);
                    AssemblyStore asseStore = flowMapper.findStoreBySheetId(sheet.getId());
                    AssemblyStoreRecord storeRecordP = flowMapper.findStoreRecordById(befRecord.getRecordId());
                    // 修改成品库对应数据
                    flowMapper.udpAsseStoreBySheetId(asseStore);
                    // 生产装配件入库记录(冲单)
                    AssemblyStoreRecord storeRecordM = new AssemblyStoreRecord();
                    BeanUtil.copy(storeRecordP, storeRecordM);
                    storeRecordM.setStoreType(1);
                    storeRecordM.setRecordType(2);
                    storeRecordM.setStorageTime(new Date());
                    storeRecordM.setReplaceId(storeRecordP.getId());
                    storeRecordM.setId(null);
                    flowMapper.insertStoreRecord(storeRecordM);
                }
            }
        }
        return 1;
    }

    /**
     * @methodName: getTrans
     * @description: 根据主键获取转序单
     * @param: id
     * @return： com.zw.transition.entity.FlowTrans
     * @exception：
     * @author： 徐一贺 tel:18341916590
     * @designer： 陈欣
     * @leader： 陈欣 tel:18104194240
     * @date： 2021/4/24 13:30
     * @office: 智能控制设计科
     * @research institute： 智能控制设计所
     * @department： 机械设计院
     * @company: 辽宁忠旺机械设备制造有限公司
     * @group： 忠旺集团
     * @version: 1.0
     */
    public FlowTrans getTrans(Integer id) {
        return flowMapper.getTrans(id);
    }

    /**
     * @methodName: getFlowRouteByPrimaryKey
     * @description: 根据主键获取对应的路线
     * @param: routeId
     * @return： com.zw.transition.entity.FlowRoute
     * @exception：
     * @author： 徐一贺 tel:18341916590
     * @designer： 陈欣
     * @leader： 陈欣 tel:18104194240
     * @date： 2021/4/24 13:35
     * @office: 智能控制设计科
     * @research institute： 智能控制设计所
     * @department： 机械设计院
     * @company: 辽宁忠旺机械设备制造有限公司
     * @group： 忠旺集团
     * @version: 1.0
     */
    public FlowRoute getFlowRouteByPrimaryKey(Integer routeId) {
        return flowMapper.getFlowRouteByPrimaryKey(routeId);
    }

    /**
     * @methodName: getNextFlowRouteByBefore
     * @description: 根据上序获取下序
     * @param: currentFlowRoute
     * @return： com.zw.transition.entity.FlowRoute
     * @exception：
     * @author： 徐一贺 tel:18341916590
     * @designer： 陈欣
     * @leader： 陈欣 tel:18104194240
     * @date： 2021/4/24 13:38
     * @office: 智能控制设计科
     * @research institute： 智能控制设计所
     * @department： 机械设计院
     * @company: 辽宁忠旺机械设备制造有限公司
     * @group： 忠旺集团
     * @version: 1.0
     */
    public FlowRoute getNextFlowRouteByBefore(FlowRoute currentFlowRoute) {
        return flowMapper.getNextFlowRouteByBefore(currentFlowRoute);
    }

    /**
     * @methodName: getFirstFlowTransBySheetId
     * @description: 获取首道序的转序单
     * @param: id
     * @return： com.zw.transition.entity.FlowTrans
     * @exception：
     * @author： 徐一贺 tel:18341916590
     * @designer： 陈欣
     * @leader： 陈欣 tel:18104194240
     * @date： 2021/5/21 13:01
     * @office: 智能控制设计科
     * @research institute： 智能控制设计所
     * @department： 机械设计院
     * @company: 辽宁忠旺机械设备制造有限公司
     * @group： 忠旺集团
     * @version: 1.0
     */
    public FlowTrans getFirstFlowTransBySheetId(Integer sheetId) {
        return flowMapper.getFirstFlowTransBySheetId(sheetId);
    }

    /**
     * @methodName: getFirstFlowRouteBySheetId
     * @description: 获取第一道序
     * @param: id
     * @return： com.zw.transition.entity.FlowRoute
     * @exception：
     * @author： 徐一贺 tel:18341916590
     * @designer： 陈欣
     * @leader： 陈欣 tel:18104194240
     * @date： 2021/5/21 13:10
     * @office: 智能控制设计科
     * @research institute： 智能控制设计所
     * @department： 机械设计院
     * @company: 辽宁忠旺机械设备制造有限公司
     * @group： 忠旺集团
     * @version: 1.0
     */
    public FlowRoute getFirstFlowRouteBySheetId(Integer sheetId) {
        return flowMapper.getFirstFlowRouteBySheetId(sheetId);
    }

    /**
     * 获取路线的第一道工序
     *
     * @param sheetId
     * @param routeId
     * @return
     */
    public FlowProcess getFirstFlowProcessBySheetIdAndRouteId(Integer sheetId, Integer routeId) {
        return flowMapper.getFirstFlowProcessBySheetIdAndRouteId(sheetId, routeId);
    }

    /**
     * 根据 transId 获取质检表信息
     *
     * @param id
     * @return
     */
    public FlowCheck getFlowCheckByTransId(Integer transId) {
        return flowMapper.getFlowCheckByTransId(transId);
    }

    /**
     * 根据质检表主键获取质检附件信息
     *
     * @param checkId
     * @return
     */
    public List<FlowCheckAttachments> findFlowCheckAttachmentsByCheckId(Integer checkId) {
        List<FlowCheckAttachments> list = flowMapper.findFlowCheckAttachmentsByCheckId(checkId);
//        for (int i = 0; i < list.size(); i++) {
//            FlowCheckAttachments att = list.get(i);
//            att.setAttUrl(serverUrl+""+att.getAttUrl());
//        }
        return list;
    }

    /**
     * 新增质检单
     *
     * @param file
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public JsonResult saveCheckOrders(MultipartFile[] files, String[] removeFiles, HttpServletRequest request) {
        User currentUser = (User) ServletUtils.getSession().getAttribute("user");
        Date currenrtDate = new Date();
        FlowCheck check = flowMapper.getFlowCheckByPrimaryKey(Integer.parseInt(request.getParameter("checkId")));
        if (request.getParameter("reason") != null && !request.getParameter("reason").equals("undefined")) {
            check.setReason(request.getParameter("reason"));
            flowMapper.updateFlowCheckReasonByPrimaryKey(check);
        }
        String afterPath = "checkOrder/" + check.getId() + "/";
        String allPath = uploadPath + afterPath;
        int parts = files.length;
        //插入数据
        for (int i = 0; i < parts; i++) {
            String upFileName = files[i].getOriginalFilename();
            if (!upFileName.equals("blob")) {
                FlowCheckAttachments dataCheckAttachments = flowMapper.getFlowCheckAttachmentsByCheckIdAndAttFileName(check.getId(), files[i].getName());
                if (dataCheckAttachments == null) {
                    FlowCheckAttachments checkAttachments = new FlowCheckAttachments();
                    checkAttachments.setCheckId(check.getId());
                    checkAttachments.setUploaderCode(currentUser.getAccount());
                    checkAttachments.setUploaderName(currentUser.getName());
                    if (currentUser.getBranch() != null) {
                        checkAttachments.setUploaderDept(currentUser.getBranch());
                    }
                    checkAttachments.setUploaderTime(currenrtDate);
                    checkAttachments.setRemark("");
                    checkAttachments.setIsDel(0);
                    String fileName = FileUtils.upload(files[i], allPath);
                    checkAttachments.setAttFileName(fileName);
                    String url = "/files/" + afterPath + fileName;
                    checkAttachments.setAttUrl(url);
                    flowMapper.insertFlowCheckAttachments(checkAttachments);
                }
            }
        }
        //删除附件
        for (int i = 0; i < removeFiles.length; i++) {
            FlowCheckAttachments remove = new FlowCheckAttachments();
            remove.setCheckId(check.getId());
            remove.setAttFileName(removeFiles[i]);
            remove.setDeleteCode(currentUser.getAccount());
            remove.setDeleteName(currentUser.getName());
            if (currentUser.getBranch() != null) {
                remove.setDeleteDept(currentUser.getBranch());
            }
            remove.setDeleteTime(currenrtDate);
            remove.setCheckId(check.getId());
            remove.setAttFileName(removeFiles[i]);
            flowMapper.deleteFlowCheckAttachmentsByCheckIdAndAttFileName(remove);
            File file = new File(allPath + removeFiles[i]);
            if (file.exists()) {
                file.delete();
            }
        }
        JsonResult jsonResult = new JsonResult();
        jsonResult.setType(JsonResult.ResultType.SUCCESS);
        jsonResult.setMsg("保存成功");
        return jsonResult;
    }

    /**
     * 根据主键获取工艺卡
     *
     * @param id
     * @return
     */
    public FlowSheet getFlowSheetByPrimaryKey(Integer id) {
        return flowMapper.getFlowSheetByPrimaryKey(id);
    }

    /**
     * 根据 工艺卡主键、路线表主键、工序主键获取对应的电子转序单数据
     *
     * @param sheetId
     * @param routeId
     * @param processId
     * @return
     */
    public FlowTrans getFlowTransBySheetIdAndRouteIdAndProcessId(Integer sheetId, Integer routeId, Integer processId) {
        return flowMapper.getFlowTransBySheetIdAndRouteIdAndProcessId(sheetId, routeId, processId);
    }

    /**
     * 根据 工艺卡主键、路线表主键、工序主键获取对应的电子转序单数据
     *
     * @param sheetId
     * @param routeId
     * @param processId
     * @return
     */
    public FlowTrans getFlowTransBySheetIdForRepair(Integer sheetId) {
        return flowMapper.getFlowTransBySheetIdForRepair(sheetId);
    }

    /**
     * 根据主键获取转序单
     *
     * @param id
     * @return
     */
    public FlowTrans getFlowTransByPrimaryKey(Integer id) {
        return flowMapper.getFlowTransByPrimaryKey(id);
    }

    /**
     * 取消申请质检 厂级
     *
     * @param flowRoute
     * @return
     */
    public int updateRouteApplyToCancelApply(FlowRoute flowRoute) {
        return flowMapper.updateRouteApplyToCancelApply(flowRoute);
    }

    /**
     * 删除转序单 厂级
     *
     * @param flowTrans
     * @return
     */
    public int updateFlowTransIsdel(FlowTrans flowTrans) {
        return flowMapper.updateFlowTransIsdel(flowTrans);
    }

    /**
     * 如果没申请质检，转序状态设置成未开始 厂级
     *
     * @param id
     * @return
     */
    public int updateRouteStatusNotStarted(Integer id) {
        return flowMapper.updateRouteStatusNotStarted(id);
    }

    /**
     * 依据主键获取工序表数据
     *
     * @param process
     * @return
     */
    public FlowProcess getFlowProcessByPrimaryKey(Integer process) {
        return flowMapper.getFlowProcessByPrimaryKey(process);
    }

    /**
     * 取消路线申请
     *
     * @param route
     * @return
     */
    public int updateCancelRouteApply(FlowRoute route) {
        return flowMapper.updateCancelRouteApply(route);
    }

    /**
     * 根据转序单去找车间级转序工序的序号
     *
     * @param currentTrans
     * @return
     */
    public FlowProcess getFlowProcessBySheetInfoAndRouteInfoAndProcessInfo(FlowTrans currentTrans) {
        return flowMapper.getFlowProcessBySheetInfoAndRouteInfoAndProcessInfo(currentTrans);
    }

    /**
     * 获取划线质检通过的,下序没接收的。
     *
     * @param prodNo
     * @param drawNo
     * @return
     */
    public List<FlowTrans> findHisCheckListByMarkingOff(String prodNo, String drawNo) {
        User u = (User) ServletUtils.getSession().getAttribute("user");
        return flowMapper.findHisCheckListByMarkingOff(u.getAccount(), prodNo, drawNo);
    }
}
